//
//  BKGDEvaluationViewController.m
//  bestkeep
//
//  Created by 毛韶谦 on 2016/11/10.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKGDEvaluationViewController.h"
#import "BKGDEvaluationTopView.h"
#import "BKGDEvaluationNormalCell.h"
#import "Mediator+BKMy.h"

NSString *const BKGDEvaluationViewCellIdentifier = @"BKGDEvaluationViewCellIdentifier";

@interface BKGDEvaluationViewController ()<UITableViewDelegate, UITableViewDataSource, UIViewControllerPreviewingDelegate, BKGDEvaluationNormalCellDelegate>

@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) NSMutableArray<BKGDEvaluationObject*> *dataArray;

@property(nonatomic,strong) BKGDEvaluationTopView *topView;

@property(nonatomic,assign) BOOL isLoadedData;//是否已经首次请求到数据

#pragma -mark 分页
@property(nonatomic,assign) NSInteger currentPage;//当前第几页 从1开始
@property(nonatomic,assign) NSInteger pageSize;//每页最大行

#pragma -mark 3D-Touch
@property(nonatomic,assign) NSInteger previewingIndex;//3D-Touch预览中的图片索引
@property(nonatomic,strong) NSIndexPath *previewingIndexPath;//3D-Touch预览中的tableView索引

@end

@implementation BKGDEvaluationViewController

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if(!_isLoadedData) {
        _isLoadedData = YES;
        [self requestEvaluationTop];
        [self requestEvaluationListWithPageNo:1];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeComponent];
}

#pragma -mark initialize

-(void)initializeComponent {
    
    _dataArray = [NSMutableArray array];
    
    _currentPage = 1;
    _pageSize = 10;
    
    _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor clearColor];
    [_tableView registerClass:[BKGDEvaluationNormalCell class] forCellReuseIdentifier:BKGDEvaluationViewCellIdentifier];
    [self.view addSubview:_tableView];
    
    if(!UIEdgeInsetsEqualToEdgeInsets(UIEdgeInsetsZero, _contentInset)) {
        [self setContentInset:_contentInset];
    }
    
    _topView = [[BKGDEvaluationTopView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 0)];
    
//    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestNextPage)];
//    footer.hidden = YES;
//    [footer setTitle:BKGDLocalizedString(@"BKGDEvaluationFooterRefreshNoMoreData") forState:MJRefreshStateNoMoreData];
//    _tableView.mj_footer = footer;
    
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestNextPage)];
    footer.stateLabel.textColor = LoadMoreDataTitleColor;
    footer.stateLabel.font = [UIFont systemFontOfSize:14];
    footer.arrowView.image = [UIImage imageNamed:@"BKGDPullDown"];
    UIActivityIndicatorView *loadingView = [footer valueForKeyPath:@"loadingView"];
    loadingView.hidesWhenStopped = YES;
    loadingView.color = IndictorViewColor;
    [footer addSubview:loadingView];
    self.tableView.mj_footer = footer;
    self.tableView.mj_footer.automaticallyHidden = YES;
    
    
    [self makeConstraints];
    
    [self registerForPreviewing];
}

-(void)makeConstraints {
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(UIEdgeInsetsZero);
    }];
}

-(void)setContentInset:(UIEdgeInsets)contentInset {
    _contentInset = contentInset;
    if(_tableView) {
        _tableView.contentInset = _contentInset;
        _tableView.scrollIndicatorInsets = _contentInset;
    }
}

#pragma -mark 3D-Touch

/**
 注册3D-Touch
 */
-(void)registerForPreviewing {
    if([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0) {
        [self registerForPreviewingWithDelegate:self sourceView:_tableView];
    }
}

/**
 Peek
 */
-(UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location {
    
    NSIndexPath *indexPath = [_tableView indexPathForRowAtPoint:location];
    if(!indexPath) {
        return nil;
    }
    
    _previewingIndexPath = indexPath;
    
    BKGDEvaluationNormalCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
    CGPoint point = [cell convertPoint:location fromView:_tableView];
    
    CGRect rect;
    UIImage *image;
    NSInteger index;
    
    [cell imageItemRect:&rect image:&image index:&index atPoint:point];
    
    UIViewController *controller;
    
    if(image) {
        controller = [[UIViewController alloc] init];
        _previewingIndex = index;
        
        rect = [_tableView convertRect:rect fromView:[UIApplication sharedApplication].keyWindow];
        previewingContext.sourceRect = rect;
        
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        imageView.image = image;
        imageView.layer.masksToBounds = YES;
        imageView.layer.cornerRadius = 10;
        
        CGRect screenRect = [[UIScreen mainScreen] bounds];
        CGRect imRect = [image rectAspectFitRectForSize:CGSizeMake(CGRectGetWidth(screenRect) - 60, CGRectGetHeight(screenRect) - 100)];
        
        [controller.view addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(imRect.size);
            make.center.equalTo(controller.view);
        }];
    }
    
    return controller;
}

/**
 Pop
 */
-(void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit {
    
    BKGDEvaluationNormalCell *cell = [_tableView cellForRowAtIndexPath:_previewingIndexPath];
    [cell showImageWithIndex:_previewingIndex];
}

#pragma -mark tableView delegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(_dataArray) {
        return _dataArray.count;
    }
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CGFloat height = 0;
    
    BKGDEvaluationObject *evaluation = _dataArray[indexPath.row];
    if(evaluation.cacheHeight != 0) {
        height = evaluation.cacheHeight;
    } else {
        height = [BKGDEvaluationNormalCell computeHeight:evaluation];
        evaluation.cacheHeight = height;
    }
    
    return height;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if(_dataArray.count <= 0) {
        return 0.5;
    }
    
    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.5;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BKGDEvaluationNormalCell *cell = [tableView dequeueReusableCellWithIdentifier:BKGDEvaluationViewCellIdentifier forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.delegate = self;
    
    BKGDEvaluationObject *evaluation = _dataArray[indexPath.row];
    
    [cell fillData:evaluation];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (UIView *)getViewWhenDataEndLoading {
    
    UIView *noMoreView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - _topView.frame.size.height)];
    noMoreView.backgroundColor = [UIColor colorWithRed:0.949 green:0.949 blue:0.949 alpha:1.00];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth*0.488f, ScreenWidth*0.488f)];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    UILabel *promptLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 15)];
    [noMoreView addSubview:promptLabel];
    promptLabel.text = BKGDLocalizedString(@"BKGDEvaluationNoData");
    [promptLabel setTextAlignment:NSTextAlignmentCenter];
    promptLabel.font = [UIFont systemFontOfSize:15];
    promptLabel.backgroundColor = [UIColor clearColor];
    promptLabel.textColor = [UIColor colorWithRed:0.698 green:0.698 blue:0.698 alpha:1.00];
    [noMoreView addSubview:imageView];
    
    CGPoint center = noMoreView.center;
    imageView.center = CGPointMake(center.x, center.y-80);
    promptLabel.center = CGPointMake(center.x, CGRectGetMaxY(imageView.frame)+17);
    imageView.image = [UIImage imageNamed:@"BKGDEvaluationNone"];
    return noMoreView;
}

#pragma -mark BKGDEvaluationNormalCell delegate

-(void)evaluationNormalCellPraiseAtCell:(BKGDEvaluationNormalCell *)cell isVote:(BOOL)isVote {
    
    if(![self isLogin]) {
        [self goToLogin];
        return;
    }
    
    NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
    
    if(isVote) {
        [HUD showErrorMessage:BKGDLocalizedString(@"BKGDEvaluationPriseError")];
    } else {
        [self requestEvaluationPraise:indexPath praise:YES];
    }
}

-(BOOL)isLogin {
    NSDictionary *userInfo = [[Mediator sharedInstance] BKMyUserInfo];
    BOOL isLogin = [userInfo[BKMyUserIsLoginKey] boolValue];
    return isLogin;
}

-(void)goToLogin
{
    __weak typeof(self) weakSelf = self;
    
    [[Mediator sharedInstance] userGoToLoginFromOrignalController:self finishBlock:^{
        if(!weakSelf) {
            return;
        }
        __strong typeof(weakSelf) strongSelf = weakSelf;
        
        [strongSelf.dataArray removeAllObjects];
        
        [strongSelf requestEvaluationListWithPageNo:1];
    }];
    
}

#pragma -mark 数据请求

/**
 获取商品评价的汇总信息
 */
-(void)requestEvaluationTop {
    
    if(!_goodsId) {
        return;
    }
    
    NSString *path = @"/goods-evaluation/top";
    NSString *urlString = [NSString stringWithFormat:@"%@%@", BKGDServicesURL, path];
    NSDictionary *parameters = @{@"goodsId": _goodsId};
    
    __weak typeof(self) weakSelf = self;
    
    [[RequestManager manager] bkDataRequest:RequestMethodPost URLString:urlString parameters:parameters success:^(id  _Nullable responseObject) {
        
        NSLog(@"评价汇总：%@",responseObject);
        if(!weakSelf) {
            return;
        }
        
        __strong typeof(weakSelf) strongSelf = weakSelf;
        
        BOOL success = [responseObject[@"success"] boolValue];
        if(success) {
            
            NSDictionary *data = responseObject[@"data"];
            
            if(data && data.count > 0) {
                BKGDEvaluationTopObject *topModel = [BKGDEvaluationTopObject mj_objectWithKeyValues:data];
                strongSelf.topView.evaluationTop = topModel;
            }
            
        }
        
    } failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
        
        NSLog(@"评价汇总错误：%@",error);
        
    }];
}

/**
 获取商品评价的列表信息（分页）
 */
-(void)requestEvaluationListWithPageNo:(NSInteger)pageNo {
    if(!_goodsId) {
        return;
    }
    
    NSString *path = @"/goods-evaluation/list";
    NSString *urlString = [NSString stringWithFormat:@"%@%@", BKGDServicesURL, path];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    NSDictionary *userInfo = [[Mediator sharedInstance] BKMyUserInfo];
    NSString *userId = userInfo[BKMyUserInfoGetUserIdKey];
    if(userId && ![userId isEqualToString:@""]) {
        [parameters setObject:userId forKey:@"userId"];
    }
    
    [parameters setObject:_goodsId forKey:@"goodsId"];
    [parameters setObject:@(pageNo) forKey:@"pageNo"];
    [parameters setObject:@(_pageSize) forKey:@"pageSize"];
    
    __weak typeof(self) weakSelf = self;
    
    if(pageNo == 1) {
        [LoadingView loadingShoppingCartInView:self.view];
    }
    
    [[RequestManager manager] bkDataRequest:RequestMethodPost URLString:urlString parameters:parameters success:^(id  _Nullable responseObject) {
        
        NSLog(@"评价列表：%@", responseObject);
        
        
        if(!weakSelf) {
            return;
        }
        
        [LoadingView dismiss];
        
        __strong typeof(weakSelf) strongSelf = weakSelf;
        
        BOOL success = [responseObject[@"success"] boolValue];
        if(success) {
            
            strongSelf.currentPage = pageNo;
            
            NSDictionary *data = responseObject[@"data"];
            if(!data || data.count == 0) {
                return;
            }
            
            NSArray *list = data[@"list"];
            if(!list || list.count == 0) {
                return;
            }
            
            NSMutableArray *indexPathArray = [NSMutableArray array];
            
            for (NSDictionary *dict in list) {
                BKGDEvaluationObject *evaluation = [BKGDEvaluationObject mj_objectWithKeyValues:dict];
                
                [strongSelf.dataArray addObject:evaluation];
                
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:strongSelf.dataArray.count - 1 inSection:0];
                [indexPathArray addObject:indexPath];
            }
            if(pageNo <= 1) {
                [strongSelf.tableView reloadData];
            } else {
                [strongSelf.tableView insertRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationNone];
            }
            
            NSInteger count = [data[@"total"] integerValue];
            
            if(count <= 0) {
                strongSelf.tableView.tableFooterView = [strongSelf getViewWhenDataEndLoading];
            } else {
                strongSelf.tableView.tableFooterView = nil;
                CGRect topViewFrame = strongSelf.topView.frame;
                topViewFrame.size.height = 110;
                strongSelf.topView.frame = topViewFrame;
                strongSelf.tableView.tableHeaderView = strongSelf.topView;
                
            }
            
            if(strongSelf.dataArray.count < count) {
                strongSelf.tableView.mj_footer.hidden = NO;
                [strongSelf.tableView.mj_footer endRefreshing];
            } else {
                [strongSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            
        } else {
            [strongSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            if(strongSelf.dataArray.count <= 0) {
                strongSelf.tableView.tableFooterView = [strongSelf getViewWhenDataEndLoading];
            }
        }

        
    } failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
        NSLog(@"评价列表错误：%@", error);
        
        if(!weakSelf) {
            return;
        }
        
        [LoadingView dismiss];
        
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if(!strongSelf.tableView.mj_footer.hidden) {
            [strongSelf.tableView.mj_footer endRefreshing];
        }

    }];
}

/**
 请求下一页数据
 */
-(void)requestNextPage {
    
    NSInteger page = _currentPage + 1;
    
    [self requestEvaluationListWithPageNo:page];
}


/**
 点赞
 
 @param indexPath 评价cell索引
 @param flag      点赞或者取消 （目前没有取消 只传YES即可）
 */
-(void)requestEvaluationPraise:(NSIndexPath*)indexPath praise:(BOOL)flag {
    BKGDEvaluationObject *evaluation = _dataArray[indexPath.row];
    if(!evaluation) {
        return;
    }
    
    NSString *urlString = [NSString stringWithFormat:@"%@/evaluation/add-evaluation-help", BKGDServicesURL];
    NSDictionary *userInfo = [[Mediator sharedInstance] BKMyUserInfo];
    NSString *st = userInfo[BKMyUserGetBestKeepPlateformSTKey];
    if(st) {
        st = @"";
    }
    
    NSDictionary *parameters = @{@"orderEvaluationId": evaluation.id, @"helpFlag": [NSNumber numberWithBool:flag], @"st":st};
    
    __weak typeof(self) weakSelf = self;
    
    [[RequestManager manager] bkDataRequest:RequestMethodPost URLString:urlString parameters:parameters success:^(id  _Nullable responseObject) {
        
        if(!weakSelf) {
            return;
        }
        __strong typeof(weakSelf) strongSelf = weakSelf;
        
        BOOL success = [responseObject[@"success"] boolValue];
        if(!success) {
            
            NSString *msg = responseObject[@"errorMsg"];
            if(msg) {
                [HUD showErrorMessage:msg];
            }
            
            return;
        }
        
        evaluation.isVote = YES;
        evaluation.helpfulnessNum += 1;
        
        [strongSelf.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        
    } failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
        
        NSLog(@"%@",error);
    }];
    
}

@end
